package org.openfans.web;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.domain.FansSnippet;
import org.openfans.domain.Snippet;
import org.openfans.util.ThreadFans;
import org.openfans.web.form.SnippetForm;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class SaveSnippetFormController extends SimpleFormController {
	private Facade facade = null;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public SaveSnippetFormController() {
		setCommandName("snippetForm");
		setCommandClass(SnippetForm.class);
	}

	@Override
	protected ModelAndView processFormSubmission(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		SnippetForm sf = (SnippetForm) command;
		Fans fans = facade.getFans(ThreadFans.get().getFansId());
		FansSnippet fs = new FansSnippet();
		fs.setTagSet(facade.getTagSet(sf.getTagStr(), fans));
		fs.setFans(fans);
		fs.setDescn(sf.getDescn());
		fs.setSnippetDate(new Date());
		fs.setTitle(sf.getTitle());
		fs.setPrivat(sf.isPrivateSnippet());
		Snippet s = new Snippet();
		s.setUrl(sf.getUrl());
		fs.setSnippet(s);
		facade.addFansSnippet(fs);
		return new ModelAndView(getSuccessView());
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		ThreadFans.authorize();
		SnippetForm sf = new SnippetForm();
		String idStr = request.getParameter("id");
		if (null != idStr) {
			int id = Integer.parseInt(idStr);
			Snippet s = facade.getSnippet(id);
			sf.setUrl(s.getUrl());
			sf.setDescn(s.getDescn());
		} else {
			String title = request.getParameter("title");
			title = encode(title);
			String url = request.getParameter("url");
			url = encode(url);
			String descn = request.getParameter("descn");
			descn = encode(descn);
			sf.setTitle(title);
			sf.setDescn(descn);
			sf.setUrl(url);
		}
		return sf;
	}

	private String encode(String str) throws UnsupportedEncodingException {
		if (null != str) {
			str = new String(str.getBytes("ISO-8859-1"), "UTF-8");
			;
		}
		return str;
	}
}
